﻿// Copyright (c) 2009 Kjetil Eraker Samuelsen
// This source is subject to the Microsoft Public License.
// See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.
// All other rights reserved.


using System;
using System.Collections.Generic;

using Microsoft.Office.Interop.Outlook;
using Microsoft.Office.Core;

using OutlookLib = Ksamuelsen.Office.Outlook;

namespace Ksamuelsen.Office.Outlook.Addin.VDialer {
    class VDialerItemContextMenuHandler : OutlookLib.OutlookItemContextMenuHandler {
        private CommandBarPopup    _ctxMenu = null;
        private CommandBarButton[] _buttons = null;
        private ContactInfo        _contact = null;


        public VDialerItemContextMenuHandler(Microsoft.Office.Interop.Outlook.Application app) : base(app){
        }

        protected override void OnItemContextMenuDisplay(Microsoft.Office.Core.CommandBar cmd, Microsoft.Office.Interop.Outlook.Selection sel) {
            if ((sel.Count == 1) && (sel[1] is ContactItem)) {
                int idx = 0;
                
                _contact = new ContactInfo((ContactItem)sel[1]);

                if (_contact.HasPhoneNumbers) {
                    _ctxMenu = AddCommandBarPopup(cmd, Properties.Resources.MENU_CONTEXT_TITLE, null);

                    _buttons = new CommandBarButton[_contact.PhoneNumbers.Count];

                    foreach (ContactInfo.PhoneNumber number in _contact.PhoneNumbers) {
                        CommandBarButton btn = AddCommandBarButton(_ctxMenu, number.ToString(), idx.ToString());
                        btn.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(OnDialNumber);
                        _buttons[idx++] = btn;
                    }
                }
            }
        }

        protected override void OnContextMenuClose(Microsoft.Office.Interop.Outlook.OlContextMenu ctxMenu) {
            if (ctxMenu.Equals(OlContextMenu.olItemContextMenu)) {
                if (_ctxMenu != null) {
                    foreach (CommandBarButton btn in _buttons) {
                        btn.Click -= new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(OnDialNumber);
                    }
                    _contact = null;
                    _buttons = null;
                    _ctxMenu = null;

                }

            }

        }

        private void OnDialNumber(CommandBarButton btn, ref bool CancelDefault) {
            _contact.SelectedIndex = int.Parse(btn.Tag);
            Dialer dialer = new Dialer(_contact);
            dialer.Dial();
        }


    }
}
